#include<iostream>
#include<string>
#include<memory>
#include<ctime>
#include"Socket.hpp"
#include"Protocol.hpp"
#include"InetAddr.hpp"

using namespace socket_ns;
using namespace protocol_ns;

void Uasge(std::string proc)
{
    std::cout<<"Usage\n\t"<<proc<<"serverip serverport"
        <<std::endl;
}
int main(int argc,char *argv[])
{
    if(argc!=3)
    {
        Uasge(argv[0]);
        exit(1);
    }
    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);
    InetAddr serveraddr(serverip,serverport);
    Factory factory;//工厂类
    std::unique_ptr<Socket> cli = std::make_unique<TcpSocket>();
    bool res = cli->BuildClientSocket(serveraddr);
    std::string inbuffer;
    while (res)
    {
        sleep(1);
        auto req =factory.BuildRequest();
        //请求序列化
        std::string send_str;
        req->Serialize(&send_str);
        std::cout<<"serialize: \n"<<send_str<<std::endl;
        //添加长度报头
        send_str = Encode(send_str);
        std::cout<<"Encode:\n"<<send_str<<std::endl;
        cli->Send(send_str);

        //读取应答
        int n = cli->Recv(&inbuffer);
        if(n<=0)
        {
            break;
        }
        std::string package = Decode(inbuffer);
        if(package.empty())
        continue;
        //保证package一定是一个完整的应答
        auto resp = factory.BuildResponse();
        //反序列化
        resp->Deserialize(package);
        std::cout<<resp->_result<<"["<<resp->_cond<<"]"<<std::endl;
    }
    

    return 0;
}
